/*
 * @Author: 郝奔 1425466221@qq.com
 * @Date: 2024-11-29 10:20:27
 * @LastEditors: 郝奔 1425466221@qq.com
 * @LastEditTime: 2024-12-26 14:00:07
 * @FilePath: /HG-dqbasic_open_platform/src/framework/store/modules/websocket.ts
 * @Description: 
 * Copyright (c) 2024-present HBIS Digital Technology Co.,Ltd. All rights reserved. 
 */
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getToken } from '@/framework/utils/auth'; // get token from cookie
import { unReadMessage } from '@/framework/unified-navigation/views/components/unread-message/api/index'
// setup
export const useWebsocketStore = defineStore('websocket', () => {
  // state
  // const websock: WebSocket = ref(); // 用于存储实例化后websocket
  const websock = ref<WebSocket | null>(null);
  const url = ref('');
  const lockReconnect = ref(false); // 是否真正建立连接
  const timeout = ref(25 * 1000); // 25秒一次心跳
  const timeoutObj = ref(); // 心跳心跳倒计时
  const serverTimeoutObj = ref(); // 心跳倒计时
  const timeoutnum = ref();
  const message = ref({});
  const isUnReadMessage = ref(0); // 是否有未读消息
  //actions
  function WEBSOCKET_INIT(urlpath: string): void {
    websock.value = new WebSocket(urlpath);
    url.value = urlpath;
    websock.value.onopen = function (): void {
      // 发送心跳包
      start();
    };
    websock.value.onmessage = function (callBack): void {
      //   that.commit('websocket/reset');
      reset();
      if (callBack.data == '') {
        return;
      }
      message.value = callBack.data;
      const newmsg = JSON.parse(callBack.data);
      if (callBack.data && newmsg.data && newmsg.data.messageId) {
        unReadMessage().then(res => {
          isUnReadMessage.value = res.data;
        });
      }
    };
    websock.value.onerror = function (): void {
      // e错误
      //   that.commit('websocket/reconnect');
      reconnect();
    };
    websock.value.onclose = function (): void {
      // e关闭
      // 如果
      const hasToken = getToken();
      if (hasToken) {
        // that.commit('websocket/reconnect');
        reconnect();
      }
    };
  }

  function WEBSOCKET_SEND(message: string): void {
    if (websock.value && websock.value.readyState === WebSocket.OPEN) {
      websock.value.send(message);
    } else {
      // 可以添加错误处理逻辑，例如记录日志或通知用户
      console.error('WebSocket is not open, cannot send message');
    }
  }
  // function WEBSOCKET_SEND(state, message): void {
  //   websock.value.send(message);
  // }
  function reconnect(): void {
    // 重新连接
    // const that = this;
    if (lockReconnect.value) {
      return;
    }
    lockReconnect.value = true;
    // 没连接上会一直重连，设置延迟避免请求过多
    timeoutnum.value && clearTimeout(timeoutnum.value);
    // 在某个地方，你可以这样设置它
    timeoutnum.value = setTimeout(function () {
      // 新连接
      WEBSOCKET_INIT(url.value);
      lockReconnect.value = false;
    }, 5000);
  }
  function reset(): void {
    // 重置心跳
    // 清除时间
    timeoutObj.value && clearTimeout(timeoutObj.value);
    serverTimeoutObj.value && clearTimeout(serverTimeoutObj.value);
    // 心跳
    // this.commit('websocket/start');
    start();
  }
  function start(): void {
    // 开启心跳
    // const that = this;
    timeoutObj.value && clearTimeout(timeoutObj.value);
    serverTimeoutObj.value && clearTimeout(serverTimeoutObj.value);

    timeoutObj.value = setTimeout(function () {
      // 这里发送一个心跳，后端收到后，返回一个心跳消息，
      if (websock.value?.readyState == 1) {
        // 如果连接正常
        let data = '';
        data = '{"clientMsgType":"299999"}';
        websock.value.send(data);
        serverTimeoutObj.value = setTimeout(function () {
          // 超时关闭
          websock.value?.close();
        }, timeout.value);
      } else {
        // 否则重连
        // that.commit('websocket/reconnect');
        reconnect();
      }
    }, timeout.value);
  }
  function setIsUnReadMessage(data: number): void {
    if (data > 0) {
      isUnReadMessage.value = data;
    } else {
      isUnReadMessage.value = 0;
    }
  }
  return {
    isUnReadMessage,
    setIsUnReadMessage,
    WEBSOCKET_SEND,
    WEBSOCKET_INIT
  };
});
